package com.zeng.springboot03web.dao;

import com.zeng.springboot03web.pojo.Department;
import com.zeng.springboot03web.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

// 被Spring 托管 才可以用 @Autowired
@Repository
public class EmployeeDao {
    // 初始化数据：模拟数据库中的数据

    // 在初始化时加载，需要static；库需要map实现
    private static Map<Integer, Employee> employees = null ;

    // 首先员工有所属部门
    @Autowired  // 可以使用DepartmentDao了
    private DepartmentDao departmentDao ;  // 这个操作要求这两个Dao被@Repository ➡ 被Spring托管

    // 下面赋初始值
    static {
        employees = new HashMap<>() ;  // 创建一个部门表，JDK1.8之后泛型可省略

        employees.put(13001, new Employee(13001, "AA", "aaaa@mail.com", 0, new Department(1704, "运营部"))) ;
        employees.put(13002, new Employee(13002, "BB", "bbbb@mail.com", 1, new Department(1701, "教学部"))) ;
        employees.put(13003, new Employee(13003, "CC", "dddd@mail.com", 0, new Department(1703, "教研部"))) ;
        employees.put(13004, new Employee(13004, "DD", "eeee@mail.com", 0, new Department(1705, "后勤部"))) ;
        employees.put(13005, new Employee(13005, "EE", "ffff@mail.com", 1, new Department(1702, "市场部"))) ;
        // 因为static的原因，无法用departmentDao.getDepartmentById(Integer id)方法来获取部门
    }

    /* 增删查改 */

    // 增加一个员工（主键自增）
    private static Integer initId = 13006 ;

    public void add(Employee employee) {
        if (null == employee.getId()) {
            employee.setId(initId++) ;
        }
        employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
        employees.put(employee.getId(),employee) ;
    }

    // 获得所有员工信息
    public Collection<Employee> getALL() {
        return employees.values() ;
    }

    // 通过员工id得到员工信息
    public Employee getEmployeeById(Integer id) {
        return employees.get(id) ;
    }

    // 通过员工id删除员工
    public void delete(Integer id) {
        employees.remove(id) ;
    }
}
